package admin_service

import (
	"fmt"
	"shop/common/log"
	"shop/config/constant"
	"shop/dao"
	"shop/entity"
	"shop/utils/result"
	"shop/utils/sessionutil"
)

func GetUserList(shopId, pageNo, pageSize int) *result.Result {
	list := make([]*entity.User, 0)
	total := new(int64)
	db := dao.GetDB().Table(entity.TableNameUser).Where("shop_id", shopId).Count(total)
	db.Order("last_login_time desc,create_time desc").Offset((pageNo - 1) * pageSize).Limit(pageSize).Find(&list)
	return result.Ok(entity.Page{
		Total: *total,
		List:  list,
	})
}

func UpdateUserStatus(userId int64, shopId int, newStatus int) *result.Result {
	if newStatus != constant.UserStatusNormal && newStatus != constant.UserStatusFrozen {
		return result.Fail(fmt.Sprintf("非法状态值: %d", newStatus))
	}
	user := &entity.User{}
	dao.GetDB().Model(user).Where("id", userId).Where("shop_id", shopId).Find(user)
	if user.Id == 0 {
		return result.Fail("用户不存在")
	}
	if user.Status != constant.UserStatusNormal && user.Status != constant.UserStatusFrozen {
		return result.Fail(fmt.Sprintf("当前状态无法更新: %s", constant.UserStatusCN(user.Status)))
	}

	rows := dao.GetTx().Table(entity.TableNameUser).
		Where("id=? and shop_id=?", userId, shopId).
		UpdateColumn("status", newStatus).Commit().RowsAffected
	if newStatus == constant.UserStatusFrozen && rows > 0 {
		log.Infof("冻结用户, 强制下线: %v", sessionutil.Logout(userId))
	}
	return result.Ok(rows)
}
